package judger

import (
	"bytes"
	"fmt"
	"gugojudger/utils/ojchannel"
	"gugojudger/utils/ojresult"
	"os"
	"os/exec"
	"strings"
)

// Judge_TR /** path 工作区目录 infile 输入文件（测试用例）
func Judge_TR(path string, infile string) *ojresult.Result {
	xChannel := ojchannel.NewXChannel()
	result := ojresult.NewResult()
	target := path + "/Main"
	cmd := exec.Command(target)
	go inout(cmd, xChannel, infile)
	for {
		x := <-xChannel.C
		switch x.Code {
		case ojchannel.MNT_ERR:
			{
				result.SetMessage(AFG_IE, false)
				result.AddData("msg", fmt.Sprint(x.Msg))
				return result
			}
		case ojchannel.MNT_INF:
			{
				result.SetMessage(AFG_CC, true)
				result.AddData("stdout", fmt.Sprint(x.Msg))
				break
			}
		case ojchannel.MNT_FATAL:
			{
				result.SetMessage(AFG_EC, false)
				result.AddData("msg", "Target called syscall.")
				return result
			}
		case ojchannel.MNT_TIME:
			{
				result.AddData("time", fmt.Sprintf("%v", x.Msg))
				break
			}
		case ojchannel.MNT_EOF:
			{
				result.AddData("memory", fmt.Sprintf("%d", x.Msg))
				return result
			}
		}
	}

	return result
}

var stdoutBuf bytes.Buffer
var stderrBuf bytes.Buffer
var startTime int64
var endTime int64

//重定向输入输出并开始执行程序
func inout(cmd *exec.Cmd, X *ojchannel.OJChannelX, infile string) {

	stdoutBuf.Reset()
	stderrBuf.Reset()

	cmd.Stdin = strings.NewReader(infile)

	cmd.Stdout = &stdoutBuf

	cmd.Stderr = &stderrBuf

	runAndCollectTrace(cmd, X)
}

//删除目标目录
func removeTarget(path string) {
	err := os.RemoveAll(path)

	if err != nil {

	}

}

//格式化运行时间
func formatRunTime(endTime int64, startTime int64) float64 {
	tmp := float64(endTime-startTime) / 10000000
	return tmp
}
